import { refreshToken, getUserCenterInfo } from "@api/user.js";
import { login } from '@api/login.js'
import { message } from "ant-design-vue";
import router from '@router/system.js'
import moment from 'moment';
const date = new Date()

const user = {
    state: {
        userInfo: {
            name: '',
        },
        token: localStorage.getItem('userToken'),
        tokenTime: localStorage.getItem('tokenTime')
    },
    mutations: {
        setUserInfo(state, payload) {
            console.log(payload)
            state.userInfo.name = payload
        },
    },
    actions: {
        login_({ state, commit }, payload) {
            login(payload.username, payload.password).then(res => {
                console.log(res.status)
                if (res.status === 200) {
                    localStorage.setItem('userToken', res.data.token)
                    localStorage.setItem('tokenTime', moment(date).format('YYYY-MM-DD hh:mm:ss'))
                    message.success('登陆成功');
                    router.push({ name: 'home' })
                }
            }).catch(err => {
                console.log(err)
                if (err.request.status === 400) {
                    message.error('用户名或密码错误');
                }
            })
        },
        refreshToken({ state, commit }, token) {
            refreshToken({ token: token }).then(res => {
                console.log(res.data)
                localStorage.removeItem('userToken')
                localStorage.setItem('userToken', res.data.token)
            }).catch(err => {
                message.error('登录失效，请重新登录')
                router.push({ name: 'login' })
            })
        },
        getUserCenterInfo({ commit }) {
            getUserCenterInfo().then(res => {
                commit('setUserInfo', res.data.user_name)
            })
        }
    },
}
export default user